﻿using System.Linq;
using Gumini.JulaDB.Provider;
using Gumini.JulaDB.Test.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Gumini.JulaDB.Linq.Test
{
    /// <summary>
    /// A set of tests for the JulaDB LINQ provider. Each tests is based on multiple joined tables.
    /// </summary>
    [TestClass]
    public class JoinTest
    {
        private static JulaDbConnection _connection;
        private static QueryableSources _sources;
        private static CustomerOrderTestDataCreator _customerData;

        [ClassInitialize]
        public static void InitializeDatabase(TestContext context)
        {
            _connection = TestUtils.CreateTestDatabase();
            _customerData = new CustomerOrderTestDataCreator(_connection);
            _sources = new QueryableSources(_connection);
        }

        [ClassCleanup]
        public static void CleanupDatabase()
        {
            _connection.Close();
        }

        /// <summary>
        /// A simple join of two tables, returning an anonymous object.
        /// </summary>
        [TestMethod]
        public void CustomerOrderSimpleJoin()
        {
            var query = from c in _sources.Customers
                        join o in _sources.Orders on c.CustomerId equals o.CustomerId
                        select new { c.Name, o.OrderId };
            var list = query.ToList();
            Assert.AreEqual(_customerData.TotalOrderCount, list.Count);
        }

        /// <summary>
        /// A more complex join of 4 tables.
        /// </summary>
        [TestMethod]
        public void CustomerOrderAllTableJoin()
        {
            var query = from c in _sources.Customers
                        join o in _sources.Orders on c.CustomerId equals o.CustomerId
                        join oi in _sources.OrderItems on o.OrderId equals oi.OrderId
                        join p in _sources.Products on oi.ProductId equals p.ProductId
                        select new { CustomerName = c.Name, ProductName = p.Name, p.Price };
            var list = query.ToList();
            Assert.AreEqual(_customerData.TotalOrderItemCount, list.Count);
        }
    }
}
